﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VersionComparer.Base
{
    public class ServiceLocator
    {
        #region statics
        static ServiceLocator serviceLocator = new ServiceLocator ();
        public static ServiceLocator Current
        {
            get
            {
                return serviceLocator;
            }
        }
        #endregion statics

        #region fields
        private Dictionary<Type, Type> typesRegistered = new Dictionary<Type, Type>();
        #endregion statics

        #region methods
        public void Register<T, T2>()
            where T2: new()
        {
            Type typeToRegisterFrom = typeof ( T);
            Type typeToRegisterTo = typeof ( T2);
            lock (typesRegistered)
            {
                
                if ( typesRegistered.ContainsKey  (typeToRegisterFrom))
                    typesRegistered[typeToRegisterFrom ] = typeToRegisterTo;
                else
                    typesRegistered.Add(typeToRegisterFrom , typeToRegisterTo);
            }
        }

        public object CreateInstance(Type type)
        {
            Type destinationType;
            lock (typesRegistered)
            {
                if (typesRegistered.TryGetValue(type, out destinationType))
                    return Activator.CreateInstance(destinationType);
                else
                    return null;
            }
        }
        public object CreateInstance(Type type, Type defaultType)
        {
            object newInstance = CreateInstance(type);
            if (newInstance == null)
                return Activator.CreateInstance ( defaultType );
            else
                return newInstance;
        }
        public T CreateInstance<T>()
            where T : class
        {
            return CreateInstance(typeof(T)) as T;
        }

        
        public T CreateInstance<T, DefaultT>()
            where T:class, new ()
            where DefaultT: T, new()
        {
            return CreateInstance(typeof(T), typeof(DefaultT)) as T;

        }
        #endregion methods
    }
}
